package com.panopset.io;

import static com.panopset.UtilIO.*;

import java.io.File;
import java.io.StringWriter;

import com.panopset.Strings;

/**
 * Global replace directory processor.
 *
 * @author Karl Dinwiddie.
 *
 */
public final class GlobalReplace extends DirectoryProcessor {

    /**
     * From String.
     */
    private final String from;

    /**
     * To String.
     */
    private final String to;

    /**
     * Extension to limit file types to.
     */
    private final String ext;

    /**
     * @param dir
     *            Directory to traverse.
     * @param fromText
     *            String to replace.
     * @param toText
     *            Replacement String.
     * @param extension
     *            File type to limit processing to, for example
     *            &quot;.txt&quot;. All files will be processed if extension is
     *            null or blank.
     */
    public GlobalReplace(final File dir, final String fromText,
            final String toText, final String extension) {
        super(dir);
        from = fromText;
        to = toText;
        this.ext = extension;
    }

    @Override
    protected void process(final File f) {
        if (com.panopset.Util.getExtension(f).equals(ext)) {
            final StringWriter sw = new StringWriter();
            new FileProcessor.Builder().fileAndListener(f,
                    new FileProcessor.Listener() {

                        @Override
                        public void process(final FileProcessor processor,
                                final String[] values) {
                            for (String s : values) {
                                sw.append(s.replace(from, to));
                                sw.append(Strings.getEol());
                            }
                        }

                        @Override
                        public void finish(final FileProcessor processor) {
                            // nothing to do here.
                        }

                    }).construct().exec();
            saveStringToFile(sw.toString(), f);
        }
    }

}
